<?php
namespace app\common\model;
use think\Model;
class Score extends Model{
    // 定义时间戳字段名
    protected $createTime = '';
    protected $updateTime = '';
	// 自动完成
	protected $auto = ['score_addtime'];
	protected $insert = [];
	protected $update = [];
	public $fieldlist = [
	    1=>'注册赠送',2=>'影币充值',3=>'付费点播',4=>'VIP升级',5=>'管理员操作',6=>'积分返还',7=>'管理补单',
	    8=>'卡密充值',9=>'推广注册',10=>'推广访问',11=>'注册赠送VIP',12=>'评论赠送',13=>'发布剧情',14=>'发布角色',15=>'发布话题',16=>'发布台词',17=>'发布主题曲'
	];	
	protected function setScoreAddtimeAttr(){
        return time();
    }
    public function getScoreTypeTextAttr($value,$data){
		$fieldlist=$this->fieldlist;
        return $fieldlist[$data['score_type']];
    }	
	//事件注册
    protected static function init(){
		//删除后置事件
        Score::afterDelete(function ($score){
			$user_score = model('score')->score_sum('score_uid='.$score->score_uid);
            model('user')->where('user_id='.$score->score_uid)->setField('user_score',$user_score);
       });	
    }	
	//更新影币记录及用户影币
	public function user_score($uid,$type,$ext,$sid=0,$did=0){
		if(!empty($sid) && !empty($did)){
			$data=db('score')->where(['score_uid'=>$uid,'score_sid'=>$sid,'score_did'=>$did])->find();
			if($data['score_id']){
				return false;
			}
		}
		if($ext < 0){
			$ext_total=$this->score_sum('score_uid='.$uid);
			if(abs($ext) > $ext_total){
			   $this->error = ['msg'=>"影币不足，共需要".abs($ext)."积分，请先冲值！",'code'=>-2];
			   return false;				
			}
		}
		$user=model('user');
		if($this->score_insert($uid, $type, $ext, $sid, $did)!== false){
			$user_score = $this->score_sum('score_uid='.$uid);
			if($user->where('user_id='.$uid)->setField('user_score',$user_score)!== false){
				    return $user_score;
				}else{
			        $this->error = $user->getError();
			        return false;					
			}		
		}else{
			$this->error = $this->getError();
			return false;					
		}		
	}
	//新增影币日志记录
	public function score_insert($uid,$type,$ext,$sid=0,$did=0){
		if($type==11 && $GLOBALS['config']['user']['sys']['user_cm_score_day']){
			$where = array();
			$where['score_uid']=$uid;
			$where['score_type']=$type;
			$extcount=$this->where($where)->whereTime('score_addtime','today')->sum('score_ext');
			if($extcount >= intval($GLOBALS['config']['user']['sys']['user_cm_score_day'])){
			    return false;	
			}
		}
		$data = array();
		$data['score_uid'] = $uid;
		$data['score_type'] = $type;
		$data['score_ext'] = $ext;
		$data['score_sid'] = $sid;
		$data['score_did'] = $did;
		if($this->save($data)!== false){
			return $this->data;
		}else{
			$this->error = $this->getError();
			return false;
		}
	}	
	//统计购买记录
	public function count_score_log($score_uid,$score_type=3,$score_sid=1,$score_did=0){
		$where = array();
		$where['score_uid'] = $score_uid;
		$where['score_type'] = $score_type;
		$where['score_sid'] = $score_sid;
		$where['score_did'] = $score_did;
		return $this->where($where)->count('score_id');
	}
	//根据影币日志统计影币
	public function score_sum($where, $field='score_ext'){
		return $this->where($where)->sum($field);
	}
	public function user_viptime($user_id,$user_viptime,$user_day,$ext){
		if(abs($ext) < intval($GLOBALS['config']['user']['pay']['pay_vip_small'])){
			$this->error = ['msg'=>'续费时长不得低于'.intval($GLOBALS['config']['user']['pay']['pay_vip_small']).'天！','code'=>-1];
			return false;
		}
		$ext_conf = intval($GLOBALS['config']['user']['pay']['pay_vip_day']);
		$ext_total = $ext * $ext_conf;
		if($ext < 0){
			//扣除VIP期限退还相应的影币
			$score_type = 6;
			$ext_total = abs($ext_total);
			$ext_day = '-'.abs($ext).' day';
			if(strtotime($ext_day,$user_viptime)<time()){
			    $this->error = ['msg'=>"会员时间不足,请减少天数",'code'=>-1];
			    return false;				
			}
		}else{
			//影币不足请先充值
			if($user_day < $ext_total){
			    $this->error = ['msg'=>"影币不足，共需要".$ext_total."积分，请先冲值！",'code'=>-2];
			    return false;				
			}
			$score_type = 4;
			$ext_total = -$ext_total;
			$ext_day = '+'.abs($ext).' day';
		}
		//更新影币记录
		$info = $this->score_insert($user_id,$score_type,$ext_total,0,0);
		$user=model('user');
		//更新用户信息表
		if($info['score_id']){
			$data = array();
			$data['user_id'] = $user_id;
			$data['user_score'] = $this->score_sum('score_uid='.$user_id);
			$data['user_viptime'] = strtotime($ext_day,$user_viptime);
			//VIP过期时间小于操作时间时 以操作时间开始计算
			if($score_type == 4 && ($user_viptime < time())){
				$data['user_viptime'] = strtotime($ext_day, time());
			}
			if($data['user_viptime']>time()){
			    $data['user_groupid']=$GLOBALS['config']['user']['sys']['user_reg_vip_group'];
			}else{
				$data['user_groupid']=$GLOBALS['config']['user']['sys']['user_reg_default_group'];
			}
			if($user->save($data,['user_id' => $user_id])!== false){
				$data['user_grouptitle']=db('auth_group')->where('id',$data['user_groupid'])->value('title');
				$data['user_viptime']=date('Y/m/d H:i:s',$data['user_viptime']);
				return $data;
			}else{
				$this->error = ['msg'=>$user->getError(),'code'=>-1];
			    return false;
			}
		}
		$this->error = ['msg'=>'操作失败','code'=>-1];
		return false;
	}	
    public function user_reg_time($user_id,$user_day){
		$user=model('user');
		$ext_day = '+'.abs($user_day).' day';
		$data = array();
		$data['user_id'] = $user_id;
		$data['user_viptime'] = strtotime($ext_day, time());
		if($data['user_viptime']>time()){
			$data['user_groupid']=$GLOBALS['config']['user']['sys']['user_reg_vip_group'];
		}else{
			$data['user_groupid']=$GLOBALS['config']['user']['sys']['user_reg_default_group'];
		}		
		if($user->save($data,['user_id' => $user_id])!== false){
			$result['msg']= '操作成功';
			$result['code'] = 1;
			return $result;
		}else{
			$this->error = $user->getError();
			return false;
		}		
    }
    //数据查询	
    public function listData($tag){
		$param = zanpiancms_param_url();
		if(!is_array($tag)) {
            $tag=json_decode($tag, true);
        }
		$tag['field']= !empty($tag['field']) ? $tag['field'] : '*';
		$tag['limit']= !empty($tag['limit']) ? $tag['limit'] : 10;
		if(!empty($tag['page']) && !empty($param['order'])){
			$tag['order']='score_'.$param['order'].' desc';
		}		
		if(empty($tag['order'])){
			$tag['order']='score_addtime desc';
		}	
		$where=[];
	    if(!empty($tag['uid'])) {
		    $uids = explode(',',trim($tag['uid']));
		    if(count($uids) > 1) {
			    $where['score_uid'] = array('in',$tag['uid']);
		    }else{
			    $where['score_uid'] = array('eq',$uids[0]);
		    }
	    }					
        if(!empty($tag['addtime'])){
		    $time = explode(',',$tag['addtime']);
		    if(count($time) > 1) {
			    $where['score_addtime'] = array('between',intval(strtotime($time[0])).','.intval(strtotime($time[1])));
		    }else{
			    $where['score_addtime'] = array('gt',intval(strtotime($time[0])));
		    }			
        }	
        if(!empty($tag['page'])){
			$route=$GLOBALS['route'];
            $url=urldecode(url($route,config('params')));
		    $data = $this->join('user u','u.user_id=score_uid','LEFT')->where($where)->field($tag['field'])->order($tag['order'])->paginate($tag['limit'],false,['path'=>$url]);
		}else{
			$limit_str = intval(abs($tag['start'])).",".intval(abs($tag['limit']));
			$data = $this->join('user u','u.user_id=score_uid','LEFT')->where($where)->order($tag['order'])->limit($limit_str)->select();
		}	
		return $data;
    }
}
// +----------------------------------------------------------------------
// | ZanPianCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.zanpian.com All rights reserved.
// +----------------------------------------------------------------------
// | BBS:  <http://www.feifeicms.cc>
// +----------------------------------------------------------------------